__author__ = "Chengye zhao (chengyezhao@gmail.com)"

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from product import Product, to_str
import logging

def getHistoryListXml(list):
	s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
	s += "<products>"
	for product in list:
		s += product.printXml()
	s += "</products>"
	return s

class History(db.Model):
	url = db.StringProperty()
	category = db.IntegerProperty()
	startTime = db.DateTimeProperty()
	site = db.StringProperty()
	title = db.TextProperty()

	def printXml(self):
		s = "<product>"
		s += "<url>" + self.url.replace('&', "&amp;") + "</url>"
		s += "<site>" + to_str(self.site) + "</site>"
		s += "<title>" + self.title.replace('&', "&amp;") + "</title>"
		s += "<startTime>" + to_str(self.startTime) + "</startTime>"
		s += "<category>" + to_str(self.category) + "</category>"
		s += "</product>"
		return s

class HistoryJob(webapp.RequestHandler):
	def get(self):
		q = db.GqlQuery("SELECT * from Product")
		for product in q:
			q2 = db.GqlQuery("SELECT * from History Where url = :1", product.url)
			result = q2.fetch(1)
			if len(result) != 0:
				result[0].delete()

			history = History()
			history.url = product.url
			history.site = product.site
			history.category = product.category
			history.startTime = product.startTime
			history.title = product.title
			history.put()

		history_list = db.GqlQuery("SELECT * from History")
		self.response.out.write(getHistoryListXml(history_list))

application = webapp.WSGIApplication(
	[('/history', HistoryJob)],
	debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
